﻿@model wenzhen.Models.DiagnosisRequestDto
@{
    // 定义脉象强度映射表
    var pulseDescriptions = new Dictionary<string, string>
    {
        { "0", "无" },
        { "5", "弱" },
        { "10", "有" },
        { "20", "有力" },
        { "30", "很有力" },
        { "40", "非常顶" }
    };

    // 方法：根据值获取描述
    string GetPulseDescription(string value)
    {
        if (string.IsNullOrWhiteSpace(value)) return "无";
        return pulseDescriptions.TryGetValue(value, out var description) ? description : value;
    }
}
<h2>问诊详情(请勿直接关闭，需点右上角...分享微信好友)</h2>

<table class="diagnosis-table" diagnosis-table">
    <tr>
        <th>编号</th>
        <td>
            @(string.IsNullOrWhiteSpace(Model.StudentID) ? "无" : Model.StudentID)
            @if (!string.IsNullOrEmpty(Model.HistoryStudentIDs))
            {
                var historyList = Model.HistoryStudentIDs.Split(',').Select(s => s.Trim()).ToList();
                <br />
                <strong>旧诊：</strong>
                @foreach (var id in historyList)
                {
                    <a href="@Url.Action("Details", "Diagnosis", new { studentId = id })" class="history-link">@id</a>
                    ;
                }
            }

        </td>
    </tr>
    <tr>
        <th>姓名</th>
        <td>@(string.IsNullOrWhiteSpace(Model.Name) ? "无" : Model.Name)</td>
    </tr>
    <tr>
        <th>性别</th>
        <td id="gender">@(string.IsNullOrWhiteSpace(Model.Gender) ? "无" : Model.Gender)</td>
    </tr>
    <tr>
        <th>出生年月日(农历)</th>
        <td id="birthDate">@(string.IsNullOrWhiteSpace(Model.BirthDate) ? "无" : Model.BirthDate)</td>
    </tr>
    <tr>
        <th>生病日期(公历)</th>
        <td id="sickDate">@(string.IsNullOrWhiteSpace(Model.SickDate) ? "无" : Model.SickDate)</td>
    </tr>
    <tr>
        <th>求方时间</th>
        <td id="requestTime">@(Model.RequestTime.HasValue ? Model.RequestTime.Value.ToString("yyyy-MM-dd HH:mm") : "无")</td>
    </tr>
    <tr>
        <th colspan="2">
            <button id="toggleMeihua" style="all: unset; cursor: pointer; width: 100%;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>梅花易数卦象(求方时间起卦-张延生)</span>
                    <span id="arrow">▶</span>
                </div>
            </button>
        </th>
    </tr>
    <tr>
        <td colspan="2">
            <div id="meihuaResult" style="display: none; padding-top: 10px;">
                <!-- 卦象结果将动态显示在这里 -->
            </div>
        </td>
    </tr>

    <tr>
        <th>五运六气分析</th>
        <td>
            <button type="button" class="wuyun-btn" onclick="openWuyunCalculation()">
            🌿 出生体质及脏腑打分
            </button>
        </td>
    </tr>
   
    <tr>
        <th>出生地</th>
        <td>@(string.IsNullOrWhiteSpace(Model.BirthPlace) ? "无" : Model.BirthPlace)</td>
    </tr>
    <tr>
        <th>现所在地</th>
        <td>@(string.IsNullOrWhiteSpace(Model.CurrentLocation) ? "无" : Model.CurrentLocation)</td>
    </tr>
    <tr>
        <th>身高(cm)</th>

        <td>@(string.IsNullOrWhiteSpace(Model.Height) ? "无" : Model.Height)</td>
    </tr>
    <tr>
        <th>体重(kg)</th>

        <td>@(string.IsNullOrWhiteSpace(Model.Weight) ? "无" : Model.Weight)</td>
    </tr>
   
    <tr>
        <th>全身不舒服的症状</th>
        <td>@(string.IsNullOrWhiteSpace(Model.GeneralSymptoms) ? "无" : Model.GeneralSymptoms)</td>
    </tr>
    <tr>
        <th>目前最不舒服的症状</th>
        <td>@(string.IsNullOrWhiteSpace(Model.CurrentSymptoms) ? "无" : Model.CurrentSymptoms)</td>
    </tr>
    <tr>
        <th>胃口如何/酸胀痛或其他情况</th>
        <td>@(string.IsNullOrWhiteSpace(Model.Appetite) ? "无" : Model.Appetite)</td>
    </tr>
    <tr>
        <th>晨起口中感觉如何</th>
        <td>@(string.IsNullOrWhiteSpace(Model.MorningFeeling) ? "无" : Model.MorningFeeling)</td>
    </tr>
    <tr>
        <th>吃凉东西是否容易拉肚子</th>
        <td>@(string.IsNullOrWhiteSpace(Model.ColdSensitivity) ? "无" : Model.ColdSensitivity)</td>
    </tr>
    <tr>
        <th>睡眠情况/是否有易醒或入睡困难？</th>
        <td>@(string.IsNullOrWhiteSpace(Model.SleepIssues) ? "无" : Model.SleepIssues)</td>
    </tr>
    <tr>
        <th>大便频次/秘溏/或其他情况</th>
        <td>@(string.IsNullOrWhiteSpace(Model.StoolDetails) ? "无" : Model.StoolDetails)</td>
    </tr>
    <tr>
        <th>小便频次/清黄/或其他情况</th>
        <td>@(string.IsNullOrWhiteSpace(Model.UrineDetails) ? "无" : Model.UrineDetails)</td>
    </tr>
    <tr>
        <th>舌头正反面照片</th>
        <td>
            @if (!string.IsNullOrWhiteSpace(Model.TongueImageFront))
            {
                <div class="tongue-image-container">
                    <img src="@Url.Content(Model.TongueImageFront)" alt="舌头正面" />
                    <p>正面</p>
                </div>
            }
            @if (!string.IsNullOrWhiteSpace(Model.TongueImageBack))
            {
                <div class="tongue-image-container">
                    <img src="@Url.Content(Model.TongueImageBack)" alt="舌底反面" />
                    <p>反面</p>
                </div>
            }
        </td>
    </tr>
    <tr>
        <th>最近血压血脂等指标是否正常</th>
        <td>@(string.IsNullOrWhiteSpace(Model.BloodPressure) ? "无" : Model.BloodPressure)</td>
    </tr>
    <tr>
        <th>最近情绪？烦或者郁闷？/是否胸闷？</th>
        <td>@(string.IsNullOrWhiteSpace(Model.Emotions) ? "无" : Model.Emotions)</td>
    </tr>
    <tr>
        <th>手足冷/手足热</th>
        <td>@(string.IsNullOrWhiteSpace(Model.TemperatureSensitivity) ? "无" : Model.TemperatureSensitivity)</td>
    </tr>
    <tr>
        <th>女是否痛经/男是否经常滑精</th>
        <td>@(string.IsNullOrWhiteSpace(Model.MenstrualStatus) ? "无" : Model.MenstrualStatus)</td>
    </tr>
   
    <tr>
        <th>内心想喝热水、凉水或不喜欢喝水</th>
        <td>@(string.IsNullOrWhiteSpace(Model.WaterPreference) ? "无" : Model.WaterPreference)</td>
    </tr>
    <tr>
        <th>重要病史、发病诱因（是否做过手术）</th>
        <td>@(string.IsNullOrWhiteSpace(Model.MedicalHistory) ? "无" : Model.MedicalHistory)</td>
    </tr>
   
</table>
<h2>脉诊信息</h2>
<table class="pulse-table">
    <thead>
        <tr>
            <th>位置</th>
            <th>状态</th>
            <th>左</th>
            <th>右</th>
        </tr>
    </thead>
    <tbody>
        <!-- 寸 -->
        <tr>
            <th rowspan="3">寸</th>
            <td>浮</td>
            <td>@GetPulseDescription(Model.LeftCunFloat)</td>
            <td>@GetPulseDescription(Model.RightCunFloat)</td>
        </tr>
        <tr>
            <td>中</td>
            <td>@GetPulseDescription(Model.LeftCunMiddle)</td>
            <td>@GetPulseDescription(Model.RightCunMiddle)</td>
        </tr>
        <tr>
            <td>沉</td>
            <td>@GetPulseDescription(Model.LeftCunDeep)</td>
            <td>@GetPulseDescription(Model.RightCunDeep)</td>
        </tr>

        <!-- 关 -->
        <tr>
            <th rowspan="3">关</th>
            <td>浮</td>
            <td>@GetPulseDescription(Model.LeftGuanFloat)</td>
            <td>@GetPulseDescription(Model.RightGuanFloat)</td>
        </tr>
        <tr>
            <td>中</td>
            <td>@GetPulseDescription(Model.LeftGuanMiddle)</td>
            <td>@GetPulseDescription(Model.RightGuanMiddle)</td>
        </tr>
        <tr>
            <td>沉</td>
            <td>@GetPulseDescription(Model.LeftGuanDeep)</td>
            <td>@GetPulseDescription(Model.RightGuanDeep)</td>
        </tr>

        <!-- 尺 -->
        <tr>
            <th rowspan="3">尺</th>
            <td>浮</td>
            <td>@GetPulseDescription(Model.LeftChiFloat)</td>
            <td>@GetPulseDescription(Model.RightChiFloat)</td>
        </tr>
        <tr>
            <td>中</td>
            <td>@GetPulseDescription(Model.LeftChiMiddle)</td>
            <td>@GetPulseDescription(Model.RightChiMiddle)</td>
        </tr>
        <tr>
            <td>沉</td>
            <td>@GetPulseDescription(Model.LeftChiDeep)</td>
            <td>@GetPulseDescription(Model.RightChiDeep)</td>
        </tr>
    <th>脉诊总结</th>
    <td colspan="3" style="text-align: center;">@((string.IsNullOrWhiteSpace(Model.PulseSummary) ? "无" : Model.PulseSummary))</td>         </tr>
 
    </tbody>
    <tr>
        <th>调理建议</th>
        <td>
            <textarea id="treatmentAdvice" class="form-control" rows="3" placeholder="调理建议填写保存后，需等一段时间后才能看到">@Model.TreatmentAdvice</textarea>
            <button id="saveAdvice" class="btn btn-primary" style="margin-top: 5px;">保存</button>
        </td>
    </tr>
</table>

<style>
    .gua-image {
        font-family: monospace;
        margin: 10px 0;
    }

    .gua-section {
        margin-bottom: 24px;
        padding: 20px;
        border: 1px solid #ddd;
        border-radius: 12px;
        background-color: #fff;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
        transition: box-shadow 0.3s ease;
    }

    .gua-row {
        display: flex;
        gap: 20px;
        flex-wrap: wrap;
    }

    .gua-section {
        flex: 1;
        min-width: 300px;
        margin-bottom: 20px;
        padding: 15px;
        border: 1px solid #eee;
        background-color: #fafafa;
        border-radius: 8px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    }

        .gua-section:hover {
            box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
        }

        .gua-section h3 {
            font-size: 1.25rem;
            margin-bottom: 10px;
            color: #333;
        }

        .gua-section p, .gua-section div {
            font-size: 1rem;
            line-height: 1.6;
            color: #555;
        }
    .diagnosis-table, .pulse-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
        font-family: Arial, sans-serif;
    }

    .diagnosis-table th, .diagnosis-table td,
    .pulse-table th, .pulse-table td {
        border: 1px solid #ccc;
        padding: 8px;
        text-align: left;
        vertical-align: top;
        word-wrap: break-word; /* 防止长文本溢出 */
    }

    .gua-box {
        margin: 20px;
        padding: 15px;
        border: 1px solid #ddd;
    }

    .gua-img {
        margin: 10px 0;
    }

    .yao {
        margin: 3px 0;
    }

    .highlight {
        background: #fff3d4;
    }
    /* 高亮动爻 */
    .tiyong {
        display: flex;
        gap: 20px;
    }
    .diagnosis-table th, .pulse-table th {
        background-color: #f4f4f4;
        font-weight: bold;
    }

    .pulse-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
        font-family: Arial, sans-serif;
    }

        .pulse-table th, .pulse-table td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: center;
            vertical-align: middle;
            word-wrap: break-word;
        }

        .pulse-table th {
            background-color: #f4f4f4;
            font-weight: bold;
        }

            .pulse-table th[rowspan] {
                vertical-align: middle;
            }
    .tongue-image-container {
        display: inline-block;
        text-align: center;
        margin: 10px;
    }

        .tongue-image-container img {
            width: 200px; /* 固定宽度 */
            height: 200px; /* 固定高度 */
            object-fit: cover; /* 确保图片比例适配 */
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .tongue-image-container p {
            margin-top: 5px;
            font-size: 14px;
            color: #555;
        }

    .history-link {
        color: #007bff;
        text-decoration: none;
        margin-right: 8px;
    }

        .history-link:hover {
            text-decoration: underline;
        }
    /* 新增五运六气相关样式 */
    .wuyun-section {
        margin: 20px 0;
        padding: 15px;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
    }

    .wuyun-btn {
        background: #4CAF50;
        color: white;
        padding: 12px 24px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background 0.3s;
        margin-top: 10px;
    }

   

</style>
<script src="~/js/js-calendar-converter.js"></script>
<script>
    document.getElementById('toggleMeihua').addEventListener('click', function () {
        const content = document.getElementById('meihuaResult');
        const arrow = document.getElementById('arrow');
        if (content.style.display === 'none') {
            content.style.display = 'block';
            arrow.textContent = '▼';
        } else {
            content.style.display = 'none';
            arrow.textContent = '▶';
        }
    });
</script>


<script>
    document.getElementById('saveAdvice').addEventListener('click', async () => {
        if (!treatmentAdvice || treatmentAdvice.trim() === '') {
            alert('调理建议为空无需点保存！');
            return; // Stop execution if empty
        }
        const treatmentAdvice = document.getElementById('treatmentAdvice').value;
        const studentID = "@Model.StudentID";  // 获取当前 StudentID
        console.log('StudentID:', studentID);
        const response = await fetch('/api/diagnosis/SaveAdvice', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ studentID, treatmentAdvice })
            // body: JSON.stringify(jsonData), // 发送 JSON 数据
        });
        // const response = await fetch('/api/diagnosis/add-diagnosis', {
        //     method: 'POST',
        //     headers: {
        //         'Content-Type': 'application/json', // 确保 Content-Type 为 application/json
        //     },
        //     body: JSON.stringify(jsonData), // 发送 JSON 数据
        // });

  
        const result = await response.json();
        if (result.success) {
            alert('调理建议已保存！');
        } else {
            alert('保存失败，请重试。');
        }
    });
    function openWuyunCalculation() {
        try {
            // 1. 参数验证增强
            const validateDate = (dateStr, fieldName) => {
                if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
                    throw new Error(`${fieldName}格式应为YYYY-MM-DD`);
                }
                const date = new Date(dateStr);
                if (isNaN(date.getTime())) {
                    throw new Error(`${fieldName}包含无效日期值`);
                }
                return true;
            };

            // 2. 安全获取参数值（优先使用 value）
            const safeGetParam = (id) => {
                const element = document.getElementById(id);
                if (!element) throw new Error(`找不到参数元素：${id}`);
                return element.value ? element.value.trim() : element.innerText.trim();
            };

            // 3. 获取参数
            const params = {
                birthDate: safeGetParam('birthDate'),
                sickDate: safeGetParam('sickDate'),
                requestTime: safeGetParam('requestTime'),
                gender: safeGetParam('gender')
            };

            // 4. 日期验证
            validateDate(params.birthDate, "出生日期");
            validateDate(params.sickDate, "发病日期");

            // 处理 requestTime
            let requestTimeRaw = params.requestTime;
            if (requestTimeRaw.length < 10) {
                throw new Error("求方时间格式不完整");
            }
            params.requestTime = requestTimeRaw.substring(0, 10);

            // 5. 构建 URL
            const targetBaseUrl = 'https://wuyun.esiyi.top/WuYunLiuQiApi.ashx/index.html';
            const queryParams = new URLSearchParams({
                date1: encodeURIComponent(params.birthDate),
                date2: encodeURIComponent(params.requestTime),
                date3: '',
                radiobutton1: 2,
                radiobutton2: 1,
                radiobutton3: 1,
                radiobuttonsex: params.gender
            }).toString();

            // 6. 直接跳转（避免新窗口被拦截）
            // window.location.href = `${targetBaseUrl}?${queryParams}`;
            // 修改后：跳转到前端页面并携带参数
            const frontendUrl = `https://wuyun.esiyi.top/index.html?${queryParams}`;
            window.location.href = frontendUrl;

        } catch (error) {
            console.error('操作失败:', error.stack);
            const errorContainer = document.getElementById('wuyun-error');
            if (errorContainer) {
                errorContainer.innerHTML = `<div class="alert alert-danger">${error.message}</div>`;
                errorContainer.scrollIntoView({ behavior: 'smooth' });
            } else {
                alert(`错误：${error.message}`);
            }
        }
    }
</script>
<tr>

    <td id="meihuaResult">
        <!-- 卦象结果将动态显示在这里 -->
    </td>
</tr>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const guaNames = { 1: '乾', 2: '兑', 3: '离', 4: '震', 5: '巽', 6: '坎', 7: '艮', 8: '坤' };
        const cuoGuaMap = { 1: 8, 2: 7, 3: 6, 4: 5, 5: 4, 6: 3, 7: 2, 8: 1 };
        const guaYaoMap = {
            1: ['阳', '阳', '阳'], 2: ['阳', '阳', '阴'],
            3: ['阳', '阴', '阳'], 4: ['阳', '阴', '阴'],
            5: ['阴', '阳', '阳'], 6: ['阴', '阳', '阴'],
            7: ['阴', '阴', '阳'], 8: ['阴', '阴', '阴']
        };
     
        const explanations = {
            // 上卦-下卦组合共64种
            '乾乾': '乾为天卦：刚健过盛，注意头痛、高血压等阳亢之症。宜滋阴潜阳。',
            '乾兑': '天泽履卦：金气壅滞，易发咽痛咳嗽。宜清肺利咽。',
            '乾离': '天火同人卦：心肺燥热，注意失眠多梦。宜清心宁神。',
            '乾震': '天雷无妄卦：肝阳妄动，易怒头痛。宜平肝熄风。',
            '乾巽': '天风姤卦：外感风邪，预防感冒。宜扶正祛邪。',
            '乾坎': '天水讼卦：肾水不足，腰膝酸软。宜补肾填精。',
            '乾艮': '天山遁卦：脾胃虚寒，消化不良。宜温中健脾。',
            '乾坤': '天地否卦：阴阳不交，气滞腹胀。宜理气宽中。',
            '兑乾': '泽天夬卦：痰湿壅盛，胸胁胀满。宜化痰祛湿。',
            '兑兑': '兑为泽卦：津液失调，口干舌燥。宜生津润燥。',
            '兑离': '泽火革卦：水火不调，心悸不安。宜交通心肾。',
            '兑震': '泽雷随卦：肝胆郁结，胁痛口苦。宜疏肝利胆。',
            '兑巽': '泽风大过卦：风痰上扰，眩晕耳鸣。宜化痰熄风。',
            '兑坎': '泽水困卦：水湿困脾，肢体沉重。宜健脾利湿。',
            '兑艮': '泽山咸卦：气滞血瘀，肢体麻木。宜活血通络。',
            '兑坤': '泽地萃卦：痰湿积聚，咳喘痰多。宜化痰平喘。',
            '离乾': '火天大有卦：心火亢盛，口舌生疮。宜清心泻火。',
            '离兑': '火泽睽卦：阴虚火旺，潮热盗汗。宜滋阴降火。',
            '离离': '离为火卦：心肾不交，失眠多梦。宜交通心肾。',
            '离震': '火雷噬嗑：肝火犯胃，脘痛吞酸。宜清肝和胃。',
            '离巽': '火风鼎卦：风火相煽，目赤肿痛。宜清热明目。',
            '离坎': '火水未济卦：心肾不交，症状反复。调和阴阳。',
            '离艮': '火山旅卦：脾胃积热，便秘口干。宜泻热通便。',
            '离坤': '火地晋卦：脾虚湿盛，乏力嗜睡。宜健脾化湿。',
            '震乾': '雷天大壮卦：肝阳暴涨，中风先兆。宜镇肝熄风。',
            '震兑': '雷泽归妹卦：气逆咳喘，胸闷胁痛。宜降气平喘。',
            '震离': '雷火丰卦：肝火上炎，头痛目赤。宜清肝泻火。',
            '震震': '震为雷卦：肝风内动，抽搐震颤。宜平肝潜阳。',
            '震巽': '雷风恒卦：风痰走窜，肢体拘急。宜祛风化痰。',
            '震坎': '雷水解卦：水湿泛溢，浮肿尿少。宜利水消肿。',
            '震艮': '雷山小过卦：肝郁脾虚，腹胀纳呆。宜疏肝健脾。',
            '震坤': '雷地豫卦：土虚木乘，肠鸣腹泻。宜扶土抑木。',
            '巽乾': '风天小畜卦：风邪袭表，鼻塞流涕。宜解表宣肺。',
            '巽兑': '风泽中孚卦：痰气互结，梅核气证。宜理气化痰。',
            '巽离': '风火家人卦：肝郁化火，烦躁易怒。宜疏肝清热。',
            '巽震': '风雷益卦：肝胆湿热，黄疸胁痛。宜清热利湿。',
            '巽巽': '巽为风卦：风邪入络，肌肤麻木。宜祛风通络。',
            '巽坎': '风水涣卦：水湿泛肤，湿疹瘙痒。宜祛湿止痒。',
            '巽艮': '风山渐卦：脾虚湿困，身重乏力。宜健脾渗湿。',
            '巽坤': '风地观卦：肝脾不调，腹痛肠鸣。宜调和肝脾。',
            '坎乾': '水天需卦：肾阳虚衰，畏寒肢冷。宜温补肾阳。',
            '坎兑': '水泽节卦：水饮停聚，水肿胀满。宜温阳利水。',
            '坎离': '水火既济卦：阴阳调和，病势向愈。保持平衡。',
            '坎震': '水雷屯卦：寒凝肝脉，疝气疼痛。宜暖肝散寒。',
            '坎巽': '水风井卦：肾虚风动，眩晕耳鸣。宜滋肾熄风。',
            '坎坎': '坎为水卦：肾气衰微，腰膝冷痛。宜补肾壮阳。',
            '坎艮': '水山蹇卦：寒湿痹阻，关节冷痛。宜散寒除湿。',
            '坎坤': '水地比卦：脾肾阳虚，五更泄泻。宜温补脾肾。',
            '艮乾': '山天大畜卦：脾胃寒凝，脘腹冷痛。宜温中散寒。',
            '艮兑': '山泽损卦：气滞血瘀，胸痹心痛。宜活血化瘀。',
            '艮离': '山火贲卦：胃火上炎，牙龈肿痛。宜清胃泻火。',
            '艮震': '山雷颐卦：肝郁克脾，嗳气吞酸。宜疏肝和胃。',
            '艮巽': '山风蛊卦：湿毒内蕴，疮疡肿毒。宜解毒化湿。',
            '艮坎': '山水蒙卦：寒湿困脾，头重如裹。宜升阳除湿。',
            '艮艮': '艮为山卦：气机壅滞，便秘腹胀。宜行气导滞。',
            '艮坤': '山地剥卦：脾肾两虚，久泻不止。宜固涩止泻。',
            '坤乾': '地天泰卦：脾胃虚寒，消化不良。宜温补中焦。',
            '坤兑': '地泽临卦：痰湿壅滞，咳喘痰鸣。宜燥湿化痰。',
            '坤离': '地火明夷：阴虚血热，崩漏下血。宜凉血止血。',
            '坤震': '地雷复卦：脾虚气陷，久泻脱肛。宜升阳举陷。',
            '坤巽': '地风升卦：清阳不升，头晕目眩。宜升发清阳。',
            '坤坎': '地水师卦：水湿泛滥，全身浮肿。宜温阳利水。',
            '坤艮': '地山谦卦：中气不足，脏器下垂。宜补中益气。',
            '坤坤': '坤为地卦：气血两虚，面色萎黄。宜气血双补。'
        };
        // 爻象图形生成函数（使用SVG）
        function generateYaoImage(yaoType) {
            return yaoType === '阳' ?
                '<svg width="60" height="8"><rect width="60" height="8" fill="black"/></svg>' :
                '<svg width="60" height="8"><rect x="0" width="24" height="8" fill="black"/><rect x="36" width="24" height="8" fill="black"/></svg>';
        }

  
        function calculateGua() {

            // //         在用“年月口时起卦法”时.只用“地支”而不用“天干”。
            // //         如甲辰年辰”在“地支”中是排在第5位的、故其对应于5。
            // //         月份是阴历九月
            // //         引子是阴历二十六
            // //         现花的时间是申时。即“申”时是“地支”计时的第九个时辰。


            // //         上卦：（年数 + 月数 + 日数）除以8，余数定上卦。
            // //         下卦：（年数 + 月数 + 日数 + 时辰数）除以8，余数定下卦。
            // //         变爻的确定：（年数 + 月数 + 日数 + 时辰数）除以6，余数
            // //         定变爻的位置；
            // //         落实到我们现在的情况就应该是：
            // //         上卦：(5 + 9 + 26) = 40.40除以8，正好除尽。所以是坤卦。
            // //         下卦：(5 + 9 + 26 + 9) = 49.49除以8，余1.1“先天数”对应于乾卦。
            // //         变爻：（5 + 9 + 26 + 9) = 49.49除以6，余1。初（第一）爻变。
            // // 即上下卦重之得地天泰卦。其（一）  爻变。变为地风升卦。
            // // 因为变爻变在下卦内，故下卦巽卦为“体”卦。上卦坤卦为“用”卦。
            const timeStr = document.getElementById('requestTime').textContent;
            if (timeStr === '无') return;

            const [datePart, timePart] = timeStr.split(' ');
            const [year, month, day] = datePart.split('-').map(Number);
            const [hour] = timePart.split(':').map(Number);

            // 将阳历转为农历
            const lunar = calendar.solar2lunar(year, month, day);

            // 地支序数（用年支）
            const dizhi = "子丑寅卯辰巳午未申酉戌亥";
            const yearBranch = lunar.gzYear.charAt(1);
            const yearIndex = dizhi.indexOf(yearBranch) + 1; // 1 ~ 12

            // 农历月和日（转为数字）
            const lunarMonth = "一二三四五六七八九十冬腊".indexOf(lunar.IMonthCn.charAt(0)) + 1;
            const lunarDayStr = lunar.IDayCn;
            const lunarDay = (() => {
                const dayMap = {
                    '初': 0, '十': 10, '廿': 20, '卅': 30
                };
                const prefix = dayMap[lunarDayStr.charAt(0)] || 0;
                const suffix = "一二三四五六七八九十".indexOf(lunarDayStr.charAt(1)) + 1;
                return prefix + suffix;
            })();

            // 地支时辰序数（1 ~ 12）
            const hourBranch = (() => {
                const hourMap = [23, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21];
                for (let i = 0; i < hourMap.length; i++) {
                    if (hour >= hourMap[i] && hour < hourMap[i] + 2) {
                        return i + 1; // 1 ~ 12
                    }
                }
                return 1; // 默认子时
            })();

            // 上卦 = (年 + 月 + 日) % 8
            const upIndex = (yearIndex + lunarMonth + lunarDay) % 8 || 8;
            // 下卦 = (年 + 月 + 日 + 时) % 8
            const downIndex = (yearIndex + lunarMonth + lunarDay + hourBranch) % 8 || 8;
            // 变爻 = (年 + 月 + 日 + 时) % 6
            const changeIndex = (yearIndex + lunarMonth + lunarDay + hourBranch) % 6 || 6;
            // 变爻位置（0=初爻, 5=上爻）
            const changeYaoIndex = changeIndex - 1;

            // 生成本卦的六爻（下卦+上卦）
            const originalYao = [...guaYaoMap[downIndex], ...guaYaoMap[upIndex]];

            // 生成变卦（变爻位置阴阳互换）
            const bianYao = [...originalYao];
            bianYao[changeYaoIndex] = bianYao[changeYaoIndex] === '阳' ? '阴' : '阳';

            // 变卦的上卦和下卦
            const newShang = sanYaoToGua[bianYao.slice(3).map(y => y === '阳' ? 1 : 0).join('')];
            const newXia = sanYaoToGua[bianYao.slice(0, 3).map(y => y === '阳' ? 1 : 0).join('')];
            // 五行对应表
            const guaWuXing = {
                乾: '金', 坤: '土',
                震: '木', 巽: '木',
                坎: '水', 离: '火',
                艮: '土', 兑: '金'
            };

            // 五行判断函数
            function getWuXingRelation(ti, yong) {
                const sheng = {
                    木: '火',
                    火: '土',
                    土: '金',
                    金: '水',
                    水: '木'
                };
                const ke = {
                    木: '土',
                    土: '水',
                    水: '火',
                    火: '金',
                    金: '木'
                };

                const tiXing = guaWuXing[ti];
                const yongXing = guaWuXing[yong];

                if (ke[yongXing] === tiXing) return '用克体 → 需克服困难';
                if (sheng[tiXing] === yongXing) return '体生用 → 需努力';
                if (ke[tiXing] === yongXing) return '体克用 → 吉';
                if (sheng[yongXing] === tiXing) return '用生体 → 大吉';
                if (tiXing === yongXing) return '同五行 → 平';
                return '五行无直接生克 → 平';
            }


      

            // 确定体卦和用卦（变爻所在卦为体卦）
            let tiGua, yongGua, tiPosition;
            const yaoNames = ['初爻', '二爻', '三爻', '四爻', '五爻', '上爻'];
            const changeYaoName = yaoNames[changeYaoIndex];

            // 判断变爻位置（0-2为下卦，3-5为上卦）
            if (changeYaoIndex < 3) {
                // 变爻在下卦 → 体卦为变卦的下卦
                tiGua = guaNames[newXia];
                yongGua = guaNames[newShang];
                tiPosition = "下卦";
            } else {
                // 变爻在上卦 → 体卦为变卦的上卦
                tiGua = guaNames[newShang];
                yongGua = guaNames[newXia];
                tiPosition = "上卦";
            }

            // 获取五行吉凶判断
            const wuXingJudgement = getWuXingRelation(tiGua, yongGua);

            // 渲染结果
            document.getElementById('meihuaResult').innerHTML = `
            <div class="gua-row">
                <div class="gua-section">
                    <h3>本卦：${guaNames[upIndex]}${guaNames[downIndex]}</h3>
                    ${generateGuaImage(upIndex, downIndex)}
                    <div>${explanations[guaNames[upIndex] + guaNames[downIndex]] || '暂无解释'}</div>
                </div>
                <div class="gua-section">
                    <h3>变卦：${guaNames[newShang]}${guaNames[newXia]}</h3>
                    ${generateGuaImage(newShang, newXia)}
                    <div>${explanations[guaNames[newShang] + guaNames[newXia]] || '暂无解释'}</div>
                </div>
                <div class="gua-section">
                    <p>变爻：${changeYaoName} (位于${tiPosition})</p>
                    <h3>体卦：${tiGua} (${tiPosition})</h3>
                    <h3>用卦：${yongGua}</h3>
                    <p>五行关系：${wuXingJudgement}</p>
                </div>
            </div>
        `;
        }



        // 辅助函数：生成卦象图像
        // function generateGuaImage(shangIndex, xiaIndex) {
        //     const shangLines = guaYaoMap[shangIndex];
        //     const xiaLines = guaYaoMap[xiaIndex];

        //     let html = '<div class="gua-image">';
        //     // 上卦（从上往下画）
        //     for (let i = 2; i >= 0; i--) {
        //         html += `<div class="${shangLines[i] === '阳' ? '━ ━ ━' : '━　　━'}"></div>`;
        //     }
        //     // 下卦（从上往下画）
        //     for (let i = 2; i >= 0; i--) {
        //         html += `<div class="${xiaLines[i] === '阳' ? '━ ━ ━' : '━　　━'}"></div>`;
        //     }
        //     html += '</div>';
        //     return html;
        // }
        function generateGuaImage(shangNum, xiaNum) {
            const yaoLines = [...guaYaoMap[xiaNum], ...guaYaoMap[shangNum]]
                .reverse() // 易经卦象从下往上画
                .map(yao => {
                    return `<div class="yao-line">${yao === '阳' ? '━ ━ ━' : '━　　━'}</div>`;
                })
                .join('');

            return `<div class="gua-image">${yaoLines}</div>`;
        }
       

        const sanYaoToGua = {
            '111': 1, '110': 2, '101': 3, '100': 4,
            '011': 5, '010': 6, '001': 7, '000': 8
        };

       
    
        // function calculateGua() {
        //     const timeStr = document.getElementById('requestTime').textContent;
        //     if (timeStr === '无') return;

        //     // 时间解析和卦象计算（原有逻辑不变）
        //     const [datePart, timePart] = timeStr.split(' ');
        //     const [year, month, day] = datePart.split('-').map(Number);
        //     const [hour] = timePart.split(':').map(Number);
        //     const sumYMD = year + month + day;
        //     const shang = (sumYMD % 8) || 8;
        //     const xia = ((sumYMD + hour) % 8) || 8;

        //     // 生成卦象图形
        //     const benGuaImage = generateGuaImage(shang, xia);
        //     const cuoGuaImage = generateGuaImage(cuoGuaMap[shang], cuoGuaMap[xia]);

        //     // 互卦计算（原有逻辑）
        //     const liuYao = [...guaYaoMap[xia], ...guaYaoMap[shang]];
        //     const huShang = sanYaoToGua[liuYao.slice(2, 5).map(y => y === '阳' ? '1' : '0').join('')];
        //     const huXia = sanYaoToGua[liuYao.slice(1, 4).map(y => y === '阳' ? '1' : '0').join('')];
        //     const huGuaImage = generateGuaImage(huShang, huXia);

        //     // 渲染结果
        //     document.getElementById('meihuaResult').innerHTML = `
        //         <div class="gua-section">
        //             <strong>本卦：${guaNames[shang]}${guaNames[xia]}</strong>
        //             ${benGuaImage}
        //             <div>${explanations[guaNames[shang] + guaNames[xia]]}</div>
        //         </div>
        //         <div class="gua-section">
        //             <strong>互卦：${guaNames[huShang]}${guaNames[huXia]}</strong>
        //             ${huGuaImage}
        //             <div>${explanations[guaNames[huShang] + guaNames[huXia]]}</div>
        //         </div>
        //         <div class="gua-section">
        //             <strong>错卦：${guaNames[cuoGuaMap[shang]]}${guaNames[cuoGuaMap[xia]]}</strong>
        //             ${cuoGuaImage}
        //             <div>${explanations[guaNames[cuoGuaMap[shang]] + guaNames[cuoGuaMap[xia]]]}</div>
        //         </div>
        //     `;
        // }
        function getHourDZ(hour) {
            const hourDizhi = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
            const index = Math.floor((hour + 1) / 2) % 12;
            return hourDizhi[index];
        }

        function getYearDZ(ganzhi) {
            return ganzhi.charAt(1); // 如“甲辰”→取“辰”
        }
        calculateGua();
    });
</script>